package com.tyun.modules.sys.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tyun.common.oauth2.TokenGenerator;
import com.tyun.common.utils.ResultDTO;
import com.tyun.common.utils.ResultUtil;
import com.tyun.modules.sys.entity.SysUserToken;
import com.tyun.modules.sys.mapper.SysUserTokenMapper;
import com.tyun.modules.sys.service.ISysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * @author taocongcong
 * @create 2017-12-15 13:46
 */
@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper,SysUserToken> implements ISysUserTokenService {

    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;
    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    public ResultDTO insertToken(String userid) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        SysUserToken tokenEntity = sysUserTokenMapper.selectById(userid);
        if(tokenEntity == null){
            tokenEntity = new SysUserToken();
            tokenEntity.setUserId(userid);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            insert(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            updateById(tokenEntity);
        }
        ResultDTO r = ResultUtil.success(token);
        return r;
    }
}
